/**
 * [日历📅插件]
 *
 * api:
 * http://newdocx.appcan.cn/plugin-API/system/uexControl
 *
 * usage:
 * <1>.html==>
 * <div onclick="appcan.date.init({ele: this, format: 'yyyy-MM-dd hh:mm:ss.S'})" id="startDate"></div>
 * <div onclick="appcan.date.init({format: 'yyyy-MM-dd hh:mm:ss.S'})" id="startDate"></div>
 * <div onclick="appcan.date.init()" id="startDate"></div>
 * <div onclick="appcan.date.init({isTime: true})" id="startDate"></div>
 *
 * <2>.js====>
 * appcan.date.format(new Date(), 'yyyy-MM-dd hh:mm:ss.S');
 * appcan.date.getDateRelative(new Date(), 1);
 * appcan.date.getWeekday(new Date());
 * appcan.date.getMonthAndDay(new Date());
 * appcan.date.getDateYearMonthDay(new Date());
 * appcan.date.getWeekdayByZhou(new Date());
 *
 * @param  {[type]} $         [description]
 * @param  {[type]} exports   [description]
 * @param  {Object} module){                 var date [description]
 * @return {[type]}           [description]
 */
appcan.define('date', function ($, exports, module) {
    var MDate = {
        errorHandle: function () {
            var date = new Date();
            return {
                year: date.getFullYear(),
                month: date.getMonth(),
                day: date.getDate()
            }
        },
        /**
         * [init description]
         * @param  {[type]} param [{el: dom, format: 'yyyy/MM/dd'}]
         * @return {[type]}       [description]
         */
        init: function (param) {
            param = param || {};
            var self = this,
                date,
                caller = MDate.init.caller, // may be cause bug
                event = window.event ? window.event : caller.arguments[0],
                target = param && param.ele ? param.ele : event.target || event.srcElement || {},
                $this = $(target),
                targetText = $this.text() || $this.val();

            if (!self.caller) self.caller = caller;


            param.format = param.format || 'yyyy/MM/dd';

            // param = $.extend(_default, param);
            try {
                var dates = targetText.split('/');
                date = {
                    year: dates[0],
                    month: dates[1],
                    day: dates[2]
                };
                // alert(JSON.stringify(param.ele));
                // alert(JSON.stringify(date));
            } catch (e) {
                date = self.errorHandle();
                // alert('get text value error: ' + JSON.stringify(e));
            }

            if (!isPhone) return; // did not run on the simular platform

            self.caller.isOpen = true;

            // alert(JSON.stringify(param));
            uexControl.openDatePicker(date.year, date.month, date.day);
            appcan.ready(function () {
                uexControl.cbOpenDatePicker = function (opId, dataType, data) {
                    try {
                        var resultDate = new Date();
                        if (data) {
                            data = JSON.parse(data);
                            // alert(JSON.stringify(data));
                            // alert(JSON.stringify(param));
                            // $this.text(data.year+'/'+data.month+'/'+data.day);
                            resultDate.setFullYear(parseInt(data.year));
                            resultDate.setMonth(parseInt(data.month) - 1);
                            resultDate.setDate(parseInt(data.day));
                        }
                        var showDate = self.format(resultDate, param.format);
                        // alert(showDate);
                        if(param.isTime){
                            MDate.continueTime(showDate, $this);
                        }else{
                            $this.text(showDate);
                            $this.val(showDate);
                        }
                    } catch (e) {
                        // alert(JSON.stringify(e));
                        var showDate = self.format(new Date(), param.format);
                        if(param.isTime){
                            MDate.continueTime(showDate, $this);
                        }else{
                            $this.text(showDate);
                            $this.val(showDate);
                        }
                    }
                }
            })
        },
        // 继续选择时间
        continueTime: function (showDate, $this) {
            var _date = new Date(),
                _hour = _date.getHours(),
                _minute = _date.getMinutes();
            uexControl.openTimePicker(_hour, _minute, function(data) {
            	if(data.hour<10){data.hour='0'+data.hour}
            	if(data.minute<10){data.minute='0'+data.minute}
                showDate = showDate + ' ' + data.hour + ':' + data.minute;
                $this.text(showDate);
                $this.val(showDate);
            });
        },
        /**
         * [format 日期格式化
         * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
         * (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
         * ]
         * @param  {[type]} _date [description]
         * @param  {[type]} fmt   [description]
         * @return {[type]}       [description]
         */
        format: function (_date, fmt) {
            if (utils.type(_date) == 'date'){

            }else if(utils.type(_date) == 'string'){
                if(_date && !~_date.indexOf('T') && ~_date.indexOf('-')){
                    _date = _date.replace(/-/g, '/');
                    if(~_date.indexOf('.0')){
                        _date = _date.replace('.0', '');
                    }
                }
                _date = new Date(_date);
            }else{
                // console.error('_date type was not found');
                return '';
            }
            var o = {
                "M+": (_date.getMonth() + 1), //月份  + 1
                "d+": _date.getDate(), //日
                "h+": _date.getHours(), //小时
                "m+": _date.getMinutes(), //分
                "s+": _date.getSeconds(), //秒
                "q+": Math.floor((_date.getMonth() + 3) / 3), //季度
                "S": _date.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (_date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
    }, _exportMore = {
        /**
         * [getDateRelative 获得相对日期]
         * @param  {[type]} date     [description]
         * @param  {[type]} dayCount [description]
         * @return {[type]}          [description]
         */
        getDateRelative: function (date, dayCount) {
            date.setTime(date.getTime() + dayCount * 24 * 60 * 60 * 1000);
            return date;
        },
        /**
         * [getWeekday ]
         * @param  {[type]} date [description]
         * @return {[type]}      [description]
         */
        getWeekday: function (date) {
            var weekday = date.getDay();
            // console.log('weekday = ' + weekday);
            var dayChineseArray = ['天', '一', '二', '三', '四', '五', '六'];
            var dayChinese = dayChineseArray[weekday];
            // console.log('星期' + dayChinese);
            return '星期' + dayChinese;
        },
        /**
         * [getMonthAndDay 获得日期]
         * @param  {[type]} date [description]
         * @return {[type]}      [description]
         */
        getMonthAndDay: function (date) {
            var month = date.getMonth() + 1;
            var day = date.getDate();
            // console.log(month + '月' + day + '日');
            return month + '月' + day + '日';
        },
        /**
         * [getDateYearMonthDay 获得日期]
         * @param  {[type]} date [description]
         * @return {[type]}      [description]
         */
        getDateYearMonthDay: function (date) {
            var dateStr = date.toLocaleDateString(date);
            dateStr = dateStr.replace(/\//g, '-');
            // console.log(dateStr);
            return dateStr;
        },
        /**
         * [getWeekdayByZhou 获得周几]
         * @param  {[type]} date [description]
         * @return {[type]}      [description]
         */
        getWeekdayByZhou: function (date) {
            var weekday = date.getDay();
            // console.log('weekday = ' + weekday);
            var dayChineseArray = ['天', '一', '二', '三', '四', '五', '六'];
            var dayChinese = dayChineseArray[weekday];
            // console.log('周' + dayChinese);
            return '周' + dayChinese;
        }
    };
    var _export = {
        init: MDate.init, //.bind(this), // .bind(MDate)
        format: MDate.format
    };
    _export = Object.assign ? Object.assign(_export, _exportMore) : $.extend(_export, _exportMore);
    exports = Object.assign ? Object.assign(exports, _export) : $.extend(exports, _export);
});
